package com.min.spring.util;

import lombok.Data;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;

@Data
public class MysqlInfo {

    private Connection connection = null;
    private final static String DATABASE_NAME = "2019springtest";

    public MysqlInfo() {
        connection = buildConnection();
    }


    /**
     * 获取数据库连接Connection
     *
     * @return
     */
    private Connection buildConnection() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/" + DATABASE_NAME + "?characterEncoding=UTF-8&useSSL=false";
            String user = "root";
            String password = "root";
            return DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取连接元数据DatabaseMetaData
     *
     * @return
     */
    public DatabaseMetaData getDatabaseMetaData() {
        try {
            return connection.getMetaData();
        } catch (SQLException e) {
            return null;
        }
    }


    /**
     * 获得数据库的一些相关信息
     */
    public void getDataBaseInformations(DatabaseMetaData dbMetaData) {
        try {
            System.out.println("数据库URL: " + dbMetaData.getURL());
            System.out.println("是否允许只读:" + dbMetaData.isReadOnly());
            System.out.println("数据库的产品名称:" + dbMetaData.getDatabaseProductName());
            System.out.println("数据库的版本:" + dbMetaData.getDatabaseProductVersion());
            System.out.println("驱动程序的名称:" + dbMetaData.getDriverName());
            System.out.println("驱动程序的版本:" + dbMetaData.getDriverVersion());
            System.out.println("最大行数:" + dbMetaData.getMaxRowSize());

            System.out.println();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * show variables
     * @return
     * @throws Exception
     */
    public Map<String,String> getVariables() {
        String sql= "show variables";
        return getMysqlInfoMap(sql);
    }

    public Map<String,String> getStatus() {
        String sql= "show STATUS";
        return getMysqlInfoMap(sql);
    }

    private Map<String, String> getMysqlInfoMap(String sql) {
        Map<String,String> map = new HashMap<>();
        if (connection == null) {
            return null;
        }
        try {
            Statement state = connection.createStatement();

            ResultSet rs = state.executeQuery(sql);
            while (rs.next()) {
                map.put(rs.getString(1), rs.getString(2));
            }

            rs.close();
            state.close();
        } catch (SQLException e) {
            return null;
        }
        return map;
    }


    public void colseCon() {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


}
